"""
用户登陆
用户登出

"""
from django import forms
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
from django.shortcuts import render, redirect

from workDjango import models
from workDjango.models import UserData
from workDjango.utils import BootStrapForm
from workDjango.utils.encrypt import md5


class UserLoginForm(BootStrapForm.ManagerLoginForm):
    username = forms.CharField(
        label='用户名',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        validators=[RegexValidator(r'^[a-zA-Z0-9_-]{4,20}$', '用户名必须为4-20位字母、数字或下划线')],
        error_messages={'required': '用户名不能为空'},
        required=True
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        validators=[RegexValidator(r'^[a-zA-Z0-9_-]{4,20}$', '密码必须为4-20位字母、数字或下划线')],
        error_messages={'required': '密码不能为空'},
        required=True
    )

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return md5(pwd)


# 用户登陆
def login(request):
    if request.method == 'GET':
        form = UserLoginForm()
        return render(request, 'login.html', {'form': form})
    form = UserLoginForm(data=request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        print(username, password)
        user = UserData.objects.filter(name=username, password=password).first()
        if user:
            request.session['user_id'] = user.id
            request.session['user_name'] = user.name
            request.session["info"] = {"id": user.id, "name": user.name}
            return redirect('/system/host')
        else:
            form.add_error('username', '用户名或密码错误')
            form.add_error('password', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


# 用户登出
def logout(request):
    request.session.clear()
    return redirect("/system/login")
